package com.ll19.thread.test.demo2ThreadLocal;

import java.util.Random;

/**
 * 
 * 两个线程同时开启，对同一个类实例进行操作，虽然速度很快，只占用一个线程运行时间，但是出现竞争使得整个代码变得无用。
 * 
 * @author liukai
 * 
 */
public class ThreadDemo1 implements Runnable {
	Student student = new Student();

	public static void main(String[] agrs) {
		
		//启动两个线程对一个对象进行操作
		//student 为共享状态 共同被两个线程操作
		
		ThreadDemo1 td = new ThreadDemo1();
		Thread t1 = new Thread(td, "a");
		Thread t2 = new Thread(td, "b");
		t1.start();
		t2.start();
	}

	public void run() {
		accessStudent();
	}

	public void accessStudent() {
		String currentThreadName = Thread.currentThread().getName();
		System.out.println(currentThreadName + " is running!");
		Random random = new Random();
		int age = random.nextInt(100);
		System.out
				.println("thread " + currentThreadName + " set age to:" + age);
		this.student.setAge(age);
		System.out.println("thread " + currentThreadName
				+ " first read age is:" + this.student.getAge());
		try {
			Thread.sleep(5000);
		} catch (InterruptedException ex) {
			ex.printStackTrace();
		}
		System.out.println("thread " + currentThreadName
				+ " second read age is:" + this.student.getAge());
	}
}
